package com.ipartek.dadoweb.filtros;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class DetectBrowser
 */
public class DetectBrowser implements Filter {

	/**
	 * Default constructor.
	 */
	public DetectBrowser() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	@Override
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletResponse httpresp = (HttpServletResponse) response;
		HttpServletRequest httpreq = (HttpServletRequest) request;
		HttpSession session = httpreq.getSession();

		String path = ((HttpServletRequest) request).getRequestURL().toString();
		String userAgent = ((HttpServletRequest) request)
				.getHeader("User-Agent");

		if (detectMobile(userAgent, session)) {
			if (!(path.contains("/movil"))) {
				httpresp.sendRedirect("/DadoWeb/movil/index.jsp");
			}
		} else {
			if (path.contains("/movil")) {
				httpresp.sendRedirect("/DadoWeb/");
			}
		}

		// pass the request along the filter chain
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	@Override
	public void init(FilterConfig fConfig) throws ServletException {
	}

	private boolean detectMobile(String userAgent, HttpSession session) {
		boolean isMobile = false;

		if (userAgent.contains("Mobile")) {
			isMobile = true;
		}

		if (isMobile) {
			session.setAttribute("isMobile", "T");
		} else {
			session.setAttribute("isMobile", "F");
		}
		return isMobile;
	}

}
